package com.web.manager;

import com.web.dao.*;
import com.web.entity.*;
import com.web.manager.jpush.SendJPushMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

import static java.math.BigDecimal.ROUND_HALF_DOWN;

/**
 *快付通
 * @author FDjavaone
 * @date 2017/10/9
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class KftCoreManager {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private PlatformMapper platformMapper;
    @Autowired
    private ProfitDetailMapper profitDetailMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private CoreDetailMapper coreDetailMapper;
    @Autowired
    private MerchantDetailMapper merchantDetailMapper;
    @Autowired
    private MskBuyOrderMapper mskBuyOrderMapper;
    @Autowired
    private OriginalDetailMapper originalDetailMapper;
    @Autowired
    private ConsumptionDetailMapper consumptionDetailMapper;
    @Autowired
    private UserAccountMapper userAccountMapper;
    @Autowired
    private UserAccountRecordMapper userAccountRecordMapper;
    @Autowired
    private CompanyBonusDetailMapper companyBonusDetailMapper;
    @Autowired
    private CompanyCompanyMsDetailMapper companyCompanyMsDetailMapper;
    @Autowired
    private CompanyFundDetailMapper companyFundDetailMapper;
    @Autowired
    private CompanyMarketDetailMapper companyMarketDetailMapper;
    @Autowired
    private CompanyPoundageDetailMapper companyPoundageDetailMapper;
    @Autowired
    private CompanyProfitDetailMapper companyProfitDetailMapper;
    @Autowired
    private OrderRecordForPlatformMapper orderRecordForPlatformMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CompanyReportMapper companyReportMapper;

    public int levelCount(BigDecimal total, Member member) {
        //  会员等级
        //  1、一级“服务使者”团队消费总额190万，包括自己消费，加所有团队消费都算。               
        //  2、二级“服务大使”团队消费总额1300万，并推荐两个达到一级，符合这两个条件才可以升级。            
        //  3、三级“服务特使”团队消费总额3100万，并推荐两个达到二级，符合这两个条件才可以升级。           
        //  4、四级“服务天使”团队消费总额1.3亿，并推荐两个达到三级，符合这两个条件才可以升级。             
        //  5、五级“服务总裁”团队消费总额3.1亿，并推荐两个达到四级，符合这两个条件才可以升级。            
        // 6、六级“服务董事”团队消费总额13亿，并推荐两个达到五级，符合这两个条件才可以升级。
        int level = member.getLevel();

        if (total.compareTo(new BigDecimal("1900000")) == -1) {
            //消费小于190w,0级
            level = 0;
        } else if (total.compareTo(new BigDecimal("1900000")) != -1 && total.compareTo(new BigDecimal("13000000")) == -1) {
            //团队总消费在190w-1300w之间
            level = 1;
        } else if (total.compareTo(new BigDecimal("13000000")) != -1 && total.compareTo(new BigDecimal("31000000")) == -1) {
            //团队总消费在1300w-3100w之间
            Integer count = memberMapper.countMySub(member.getInviteCode(), 1);
            if (count >= 2) {
                level = 2;
            }
        } else if (total.compareTo(new BigDecimal("31000000")) != -1 && total.compareTo(new BigDecimal("130000000")) == -1) {
            //团队总消费在3100w-1.3亿之间
            Integer count = memberMapper.countMySub(member.getInviteCode(), 2);
            if (count >= 2) {
                level = 3;
            }
        } else if (total.compareTo(new BigDecimal("130000000")) != -1 && total.compareTo(new BigDecimal("310000000")) == -1) {
            //团队总消费在1.3亿-3.1亿之间
            Integer count = memberMapper.countMySub(member.getInviteCode(), 3);
            if (count >= 2) {
                level = 4;
            }
        } else if (total.compareTo(new BigDecimal("310000000")) != -1 && total.compareTo(new BigDecimal("1300000000")) == -1) {
            //团队总消费在3.1亿-13亿之间
            Integer count = memberMapper.countMySub(member.getInviteCode(), 4);
            if (count >= 2) {
                level = 5;
            }
        } else if (total.compareTo(new BigDecimal("1300000000")) != -1) {
            //团队总消费在13亿之上
            Integer count = memberMapper.countMySub(member.getInviteCode(), 5);
            if (count >= 2) {
                level = 6;
            }
        }
        return level;
    }

    /**累积用户自己包括团队的每个人的团队消费*/
    public void accumulateConsumeAmtAdd(BigDecimal totalPrice, Member member) {
        memberMapper.consumeAmtAdd(totalPrice, member.getId());
        int level = levelCount(member.getConsumeAmt().add(totalPrice), member);
        if (level > member.getLevel()) {
            //消费者上级的上级等级需要升级
            memberMapper.levelUp(level, member.getId());
            Message message = levelUpMessage(level, member);
            messageMapper.insertSelective(message);
            //个推信息推送
            SendJPushMessage.jPushByMessage(message);
        }
        Member memberUp = memberMapper.selectMyUp(member.getInvitedCode());
        if (memberUp != null) {
            accumulateConsumeAmtAdd(totalPrice, memberUp);
        }
    }


    public Message levelUpMessage(int memberLevel, Member member) {
        Date date = new Date();
        Message message = new Message();
        message.setModifyTime(date);
        message.setCreateTime(date);
        message.setContent("恭喜！您的等级升级到了" + memberLevel + "级");
        message.setTitle("等级提升");
        message.setFrom(0L);
        message.setFromName("系统");
        message.setTarget(member.getId());
        message.setTargetName(member.getNickName());
        return message;
    }

    public void coreOperation(Order order, BigDecimal totalPrice, BigDecimal totalBonus, BigDecimal merchantTransfer, ProfitConfig config, PoundageConfig poundageConfig
            , Platform platform, Member member, Member memberUp, Account account, Member merchant, Member merchantUp
            , RegionRecord province, RegionRecord city, RegionRecord region, Date date, Store store, CompanyReport companyReport) {

        //公司资金汇总
        companyReport.setCreateTime(date);
        companyReport.setModifyTime(date);

        BigDecimal up = new BigDecimal("0");

        //商户货款金额
        BigDecimal merchantBal = totalPrice.subtract(merchantTransfer);

        //记录分润记录
        BigDecimal profitRecord = new BigDecimal("0");
        //记录睿积分记录
        BigDecimal coreRecord = new BigDecimal("0");

        //市场资金池记录
        BigDecimal marketFundRecord = new BigDecimal("0");
        //提现手续费记录
        BigDecimal withdrawPoundageRecord = new BigDecimal("0");
        //记录消费基数记录
        BigDecimal consumeRecord = new BigDecimal("0");


        //记录扣除手续费记录
        BigDecimal merchantRecord = new BigDecimal("0");

        if (companyReport.getReserve2().equals("1")) {
            //分润
            companyReport.setProfitBal("-" + order.getTotalPrice());
            up = new BigDecimal(companyReport.getProfitBal());
            profitRecord = new BigDecimal(companyReport.getProfitBal());

        } else if (companyReport.getReserve2().equals("2")) {
            //货款
            companyReport.setUnWithdraw("-" + order.getTotalPrice());
            BigDecimal unWithdrawRecord = new BigDecimal(companyReport.getUnWithdraw());
            up = new BigDecimal(companyReport.getUnWithdraw());

        } else if (companyReport.getReserve2().equals("3")) {
            //消费
            companyReport.setConsumeBal("-" + order.getTotalPrice());
            consumeRecord = new BigDecimal(companyReport.getConsumeBal());
            up = new BigDecimal(companyReport.getConsumeBal());
            companyReport.setConsumeBal( consumeRecord.toString());
        } else if (companyReport.getReserve2().equals("4")) {
            //微信
            companyReport.setAdd(order.getTotalPrice().toString());
            merchantRecord = merchantBal.multiply(poundageConfig.getMerchantWithdraw().divide(new BigDecimal("100"))).setScale(2, ROUND_HALF_DOWN);
            up = merchantBal.multiply(poundageConfig.getMerchantWithdraw().divide(new BigDecimal("100"))).setScale(2, ROUND_HALF_DOWN);
            companyReport.setPoundage("-" + merchantRecord + "\r\n=" + "-" + accountMapper.countMerchantNum().multiply(poundageConfig.getMerchantWithdraw().divide(new BigDecimal("100"))).setScale(2, ROUND_HALF_DOWN).add(merchantRecord));

        } else if (companyReport.getReserve2().equals("5")) {
            //支付宝
            companyReport.setAdd(order.getTotalPrice().toString());
            merchantRecord = merchantBal.multiply(poundageConfig.getMerchantWithdraw().divide(new BigDecimal("100"))).setScale(2, ROUND_HALF_DOWN);
            up = merchantBal.multiply(poundageConfig.getMerchantWithdraw().divide(new BigDecimal("100"))).setScale(2, ROUND_HALF_DOWN);
            companyReport.setPoundage("-" + merchantRecord + "\r\n=" + "-" + accountMapper.countMerchantNum().multiply(poundageConfig.getMerchantWithdraw().divide(new BigDecimal("100"))).setScale(2, ROUND_HALF_DOWN).add(merchantRecord));
        }


        //用于平台追溯的交易记录
        OrderRecordForPlatform orderRecordForPlatform = new OrderRecordForPlatform();
        orderRecordForPlatform.setCreateTime(date);
        orderRecordForPlatform.setModifyTime(date);
        orderRecordForPlatform.setOrderNum(order.getOrderNum());
        orderRecordForPlatform.setConsumer(member.getName());
        orderRecordForPlatform.setConsumerPhone(member.getPhone());
        orderRecordForPlatform.setConsumeBal(order.getTotalPrice());
        orderRecordForPlatform.setTipBal(order.getTipPrice());
        orderRecordForPlatform.setTotalBal(order.getTotalPrice().add(order.getTipPrice()));
        orderRecordForPlatform.setTransferProfit(new BigDecimal(store.getLevel()).multiply(new BigDecimal("10")));
        orderRecordForPlatform.setTransferBal(merchantTransfer);
        orderRecordForPlatform.setMerchantIncome(order.getTotalPrice().add(order.getTipPrice()).subtract(merchantTransfer));
        orderRecordForPlatform.setMerchant(merchant.getName());
        orderRecordForPlatform.setMerchantPhone(merchant.getPhone());
        orderRecordForPlatform.setStore(store.getMerchantName());
        orderRecordForPlatform.setStoreId(store.getId());
        orderRecordForPlatformMapper.insertSelective(orderRecordForPlatform);


        //分配到市场资金池的金额
        BigDecimal marketBal = merchantTransfer.multiply(config.getMarketFundPool().divide(new BigDecimal("100"))).setScale(2, ROUND_HALF_DOWN);
        //分配到公司资金池的金额
        BigDecimal companyBal = merchantTransfer.multiply(config.getCompanyFundPool().divide(new BigDecimal("100"))).setScale(2, ROUND_HALF_DOWN);
        //用户的睿积分增加数量
        BigDecimal corePointsBal = merchantTransfer.multiply(config.getCorePoints().divide(new BigDecimal("100"))).setScale(2, ROUND_HALF_DOWN);


        //消费者上线得到的奖励金额
        BigDecimal memberUpProfitBal = merchantTransfer.multiply(config.getConsumeProfit().divide(new BigDecimal("100"))).setScale(2, ROUND_HALF_DOWN);
        //商户上线得到的奖励金额
        BigDecimal merchantUpProfitBal = merchantTransfer.multiply(config.getMerchantProfit().divide(new BigDecimal("100"))).setScale(2, ROUND_HALF_DOWN);
        //省市区代理获得的奖励金额
        BigDecimal provinceBal = merchantTransfer.multiply(config.getAgentProvince().divide(new BigDecimal("100"))).setScale(2, ROUND_HALF_DOWN);
        BigDecimal cityBal = merchantTransfer.multiply(config.getAgentCity().divide(new BigDecimal("100"))).setScale(2, ROUND_HALF_DOWN);
        BigDecimal regionBal = merchantTransfer.multiply(config.getAgentRegion().divide(new BigDecimal("100"))).setScale(2, ROUND_HALF_DOWN);


        //奖金获得人员的详细信息
        String bonusDetail = "";

        platform.setModifyTime(date);
        //市场资金池增加
        marketFundRecord = marketBal;
        up = up.add(marketBal);
        companyReport.setMarketFund("+" + marketFundRecord);

        platform.setMarketFundPool(platform.getMarketFundPool().add(marketBal));
        CompanyMarketDetail companyMarketDetail = new CompanyMarketDetail();
        companyMarketDetail.setCreateTime(date);
        companyMarketDetail.setModifyTime(date);
        companyMarketDetail.setContent("订单" + order.getOrderNum() + "分成");
        companyMarketDetail.setDetail("+" + marketBal);
        companyMarketDetail.setName(member.getName());
        companyMarketDetail.setPhone(member.getPhone());
        companyMarketDetail.setFromNum(order.getOrderNum());
        companyMarketDetail.setBal(platform.getMarketFundPool().toString());
        companyMarketDetail.setDescription("订单" + order.getOrderNum() + "交易商家让利分成");
        companyMarketDetailMapper.insertSelective(companyMarketDetail);

        //公司资金池增加
        up = up.add(companyBal);
        companyReport.setCompanyFund("+" + companyBal + "\r\n=" + platform.getCompanyFundPool().add(marketBal));

        platform.setCompanyFundPool(platform.getCompanyFundPool().add(companyBal));
        CompanyFundDetail companyFundDetail = new CompanyFundDetail();
        companyFundDetail.setCreateTime(date);
        companyFundDetail.setModifyTime(date);
        companyFundDetail.setContent("订单" + order.getOrderNum() + "分成");
        companyFundDetail.setDetail("+" + companyBal);
        companyFundDetail.setName(member.getName());
        companyFundDetail.setPhone(member.getPhone());
        companyFundDetail.setFromNum(order.getOrderNum());
        companyFundDetail.setDescription("订单" + order.getOrderNum() + "交易商家让利分成");
        companyFundDetail.setBal(platform.getCompanyFundPool().toString());
        companyFundDetailMapper.insertSelective(companyFundDetail);


        //如果消费者有上线且上线的等级大于等于自己，上级将获得这笔分润，再判断上级是否还有上级，该上级也将获得分润
        if (memberUp != null && memberUp.getLevel() >= member.getLevel()) {
            Account accountUp = accountMapper.selectByMid(memberUp.getId());
            totalBonus = totalBonus.add(memberUpProfitBal);
            bonusDetail += memberUp.getName() + "[" + memberUp.getPhone() + "]获得" + memberUpProfitBal + "元，";
            //分润账户资金增加
            profitRecord = profitRecord.add(memberUpProfitBal);
            up = up.add(memberUpProfitBal);
            companyReport.setProfitBal((companyReport.getProfitBal()!=null?companyReport.getProfitBal():"") + "+" + memberUpProfitBal);

            accountMapper.profitAdd(memberUpProfitBal, accountUp.getId());
            ProfitDetail profitDetailUp = new ProfitDetail();
            profitDetailUp.setModifyTime(date);
            profitDetailUp.setCreateTime(date);
            profitDetailUp.setContent("奖金");
            profitDetailUp.setDetail("+" + memberUpProfitBal);
            profitDetailUp.setaId(accountUp.getId());
            profitDetailUp.setBal(accountMapper.selectByPrimaryKey(accountUp.getId()).getProfit().toString());
            profitDetailUp.setFromNum(order.getOrderNum());
            profitDetailUp.setName(memberUp.getName());
            profitDetailUp.setPhone(memberUp.getPhone());
            profitDetailMapper.insertSelective(profitDetailUp);
            //累积奖金统计
            memberMapper.bounsAmtAdd(memberUpProfitBal, memberUp.getId());

            if (memberUp.getInvitedCode() != null) {
                //用户上线的上线
                Member memberUpUp = memberMapper.selectMyUp(memberUp.getInvitedCode());
                if (memberUpUp != null && memberUpUp.getLevel() >= memberUp.getLevel()) {

                    Account accountUpUp = accountMapper.selectByMid(memberUpUp.getId());
                    totalBonus = totalBonus.add(memberUpProfitBal);
                    bonusDetail += memberUpUp.getName() + "[" + memberUpUp.getPhone() + "]获得" + memberUpProfitBal + "元，";
                    //分润账户资金增加
                    profitRecord = profitRecord.add(memberUpProfitBal);
                    up = up.add(memberUpProfitBal);
                    companyReport.setProfitBal((companyReport.getProfitBal()!=null?companyReport.getProfitBal():"") + "+" + memberUpProfitBal);

                    accountMapper.profitAdd(memberUpProfitBal, accountUpUp.getId());
                    ProfitDetail profitDetailUpUp = new ProfitDetail();
                    profitDetailUpUp.setModifyTime(date);
                    profitDetailUpUp.setCreateTime(date);
                    profitDetailUpUp.setContent("奖金");
                    profitDetailUpUp.setDetail("+" + memberUpProfitBal);
                    profitDetailUpUp.setaId(accountUpUp.getId());
                    profitDetailUpUp.setBal(accountMapper.selectByPrimaryKey(accountUpUp.getId()).getProfit().toString());
                    profitDetailUpUp.setFromNum(order.getOrderNum());
                    profitDetailUpUp.setName(memberUpUp.getName());
                    profitDetailUpUp.setPhone(memberUpUp.getPhone());
                    profitDetailMapper.insertSelective(profitDetailUpUp);

                    //累积奖金统计
                    memberMapper.bounsAmtAdd(memberUpProfitBal, memberUpUp.getId());


                }
            }

        }

        //累积 团队消费
        accumulateConsumeAmtAdd(totalPrice, member);


        //如果商家有上线且上线的等级大于等于自己，上级将获得这笔分润，再判断上级是否还有上级,且上线的等级大于等于自己，该上级也将获得分润
        if (merchantUp != null && merchantUp.getLevel() >= merchant.getLevel()) {

            Account accountUp = accountMapper.selectByMid(merchantUp.getId());
            totalBonus = totalBonus.add(merchantUpProfitBal);

            bonusDetail += merchantUp.getName() + "[" + merchantUp.getPhone() + "]获得" + merchantUpProfitBal + "元，";
            //分润账户资金增加
            profitRecord = profitRecord.add(merchantUpProfitBal);
            up = up.add(merchantUpProfitBal);
            companyReport.setProfitBal((companyReport.getProfitBal()!=null?companyReport.getProfitBal():"") + "+" + merchantUpProfitBal);

            accountMapper.profitAdd(merchantUpProfitBal, accountUp.getId());
            ProfitDetail profitDetailUp = new ProfitDetail();
            profitDetailUp.setModifyTime(date);
            profitDetailUp.setCreateTime(date);
            profitDetailUp.setContent("奖金");
            profitDetailUp.setDetail("+" + merchantUpProfitBal);
            profitDetailUp.setaId(accountUp.getId());
            profitDetailUp.setBal(accountMapper.selectByPrimaryKey(accountUp.getId()).getProfit().toString());
            profitDetailUp.setFromNum(order.getOrderNum());
            profitDetailUp.setName(merchantUp.getName());
            profitDetailUp.setPhone(merchantUp.getPhone());
            profitDetailMapper.insertSelective(profitDetailUp);

            //累积奖金统计
            memberMapper.bounsAmtAdd(merchantUpProfitBal, merchantUp.getId());


            if (merchantUp.getInvitedCode() != null) {
                //商家的上线的上线
                Member merchantUpUp = memberMapper.selectMyUp(merchantUp.getInvitedCode());
                if (merchantUpUp != null && merchantUpUp.getLevel() >= merchantUp.getLevel()) {

                    Account accountUpUp = accountMapper.selectByMid(merchantUpUp.getId());
                    totalBonus = totalBonus.add(merchantUpProfitBal);
                    bonusDetail += merchantUpUp.getName() + "[" + merchantUpUp.getPhone() + "]获得" + merchantUpProfitBal + "元，";
                    //分润账户资金增加
                    profitRecord = profitRecord.add(merchantUpProfitBal);
                    up = up.add(merchantUpProfitBal);
                    companyReport.setProfitBal((companyReport.getProfitBal()!=null?companyReport.getProfitBal():"") + "+" + merchantUpProfitBal);

                    accountMapper.profitAdd(merchantUpProfitBal, accountUpUp.getId());
                    ProfitDetail profitDetailUpUp = new ProfitDetail();
                    profitDetailUpUp.setModifyTime(date);
                    profitDetailUpUp.setCreateTime(date);
                    profitDetailUpUp.setContent("奖金");
                    profitDetailUpUp.setDetail("+" + merchantUpProfitBal);
                    profitDetailUpUp.setaId(accountUpUp.getId());
                    profitDetailUpUp.setBal(accountMapper.selectByPrimaryKey(accountUpUp.getId()).getProfit().toString());
                    profitDetailUpUp.setFromNum(order.getOrderNum());
                    profitDetailUpUp.setName(merchantUpUp.getName());
                    profitDetailUpUp.setPhone(merchantUpUp.getPhone());
                    profitDetailMapper.insertSelective(profitDetailUpUp);
                    //累积奖金统计
                    memberMapper.bounsAmtAdd(merchantUpProfitBal, merchantUpUp.getId());

                }
            }

        }


        //若有省市区代理，活动分润
        if (province != null) {
            totalBonus = totalBonus.add(provinceBal);
            UserAccount userAccount = userAccountMapper.selectByUid(province.getuId());
            User user = userMapper.selectByPrimaryKey(province.getuId());
            bonusDetail += province.getProvince() + "代理" + user.getUsername() + "[" + user.getPhone() + "]获得" + provinceBal + "元，";
            //代理商分润累积增加
            profitRecord = profitRecord.add(provinceBal);
            up = up.add(provinceBal);
            companyReport.setProfitBal((companyReport.getProfitBal()!=null?companyReport.getProfitBal():"") + "+" + provinceBal);

            userAccountMapper.profitAdd(provinceBal, province.getuId());
            UserAccountRecord userAccountRecord = new UserAccountRecord();
            userAccountRecord.setCreateTime(date);
            userAccountRecord.setModifyTime(date);
            userAccountRecord.setDetail("代理地区" + province.getProvince() + "店铺：" + store.getMerchantName() + "消费产生分润：+" + provinceBal);
            userAccountRecord.setuAid(userAccount.getId());
            userAccountRecord.setBal(userAccountMapper.selectByPrimaryKey(userAccount.getId()).getProfit().toString());
            userAccountRecord.setName(user.getUsername());
            userAccountRecord.setPhone(user.getPhone());
            userAccountRecord.setFromNum(order.getOrderNum());
            userAccountRecordMapper.insertSelective(userAccountRecord);

        }

        if (city != null) {
            totalBonus = totalBonus.add(cityBal);
            UserAccount userAccount = userAccountMapper.selectByUid(city.getuId());
            User user = userMapper.selectByPrimaryKey(city.getuId());
            bonusDetail += city.getProvince() + city.getCity() + "代理" + user.getUsername() + "[" + user.getPhone() + "]获得" + cityBal + "元，";
            //代理商分润累积增加
            profitRecord = profitRecord.add(cityBal);
            up = up.add(cityBal);
            companyReport.setProfitBal((companyReport.getProfitBal()!=null?companyReport.getProfitBal():"") + "+" + cityBal);


            userAccountMapper.profitAdd(cityBal, city.getuId());
            UserAccountRecord userAccountRecord = new UserAccountRecord();
            userAccountRecord.setCreateTime(date);
            userAccountRecord.setModifyTime(date);
            userAccountRecord.setDetail("代理地区" + city.getProvince() + city.getCity() + "店铺：" + store.getMerchantName() + "消费产生分润：+" + cityBal);
            userAccountRecord.setuAid(userAccount.getId());
            userAccountRecord.setBal(userAccountMapper.selectByPrimaryKey(userAccount.getId()).getProfit().toString());
            userAccountRecord.setName(user.getUsername());
            userAccountRecord.setPhone(user.getPhone());
            userAccountRecord.setFromNum(order.getOrderNum());
            userAccountRecordMapper.insertSelective(userAccountRecord);
        }

        if (region != null) {

            totalBonus = totalBonus.add(regionBal);
            UserAccount userAccount = userAccountMapper.selectByUid(region.getuId());
            User user = userMapper.selectByPrimaryKey(region.getuId());
            bonusDetail += region.getProvince() + region.getCity() + "代理" + user.getUsername() + "[" + user.getPhone() + "]获得" + regionBal + "元，";
            //代理商分润累积增加
            profitRecord = profitRecord.add(regionBal);
            up = up.add(regionBal);
            companyReport.setProfitBal((companyReport.getProfitBal()!=null?companyReport.getProfitBal():"") + "+" + regionBal);

            userAccountMapper.profitAdd(regionBal, region.getuId());
            UserAccountRecord userAccountRecord = new UserAccountRecord();
            userAccountRecord.setCreateTime(date);
            userAccountRecord.setModifyTime(date);
            userAccountRecord.setDetail("代理地区" + region.getProvince() + region.getCity() + region.getRegion() + "店铺：" + store.getMerchantName() + "消费产生分润：+" + regionBal);
            userAccountRecord.setuAid(userAccount.getId());
            userAccountRecord.setBal(userAccountMapper.selectByPrimaryKey(userAccount.getId()).getProfit().toString());
            userAccountRecord.setName(user.getUsername());
            userAccountRecord.setPhone(user.getPhone());
            userAccountRecord.setFromNum(order.getOrderNum());
            userAccountRecordMapper.insertSelective(userAccountRecord);

        }


        //奖金池累积
        platform.setBonusPool(platform.getBonusPool().add(totalBonus));
        CompanyBonusDetail companyBonusDetail = new CompanyBonusDetail();
        companyBonusDetail.setCreateTime(date);
        companyBonusDetail.setModifyTime(date);
        companyBonusDetail.setContent("订单" + order.getOrderNum() + "分成");
        companyBonusDetail.setDetail("+" + totalBonus);
        companyBonusDetail.setBal(platform.getBonusPool().toString());
        companyBonusDetail.setFromNum(order.getOrderNum());
        companyBonusDetail.setDescription("订单" + order.getOrderNum() + "交易商家让利分成," + bonusDetail);
        companyBonusDetail.setName(member.getName());
        companyBonusDetail.setPhone(member.getPhone());
        companyBonusDetailMapper.insertSelective(companyBonusDetail);

        //公司利润金额
        BigDecimal companyProfitBal = merchantTransfer.subtract(totalBonus).subtract(marketBal).subtract(companyBal).subtract(corePointsBal);
        //公司利润池累积
        up = up.add(companyProfitBal);
        companyReport.setCompanyProfit("+" + companyProfitBal + "\r\n=" + platform.getCompanyProfitPool().add(companyProfitBal));

        platform.setCompanyProfitPool(platform.getCompanyProfitPool().add(companyProfitBal));
        CompanyProfitDetail companyProfitDetail = new CompanyProfitDetail();
        companyProfitDetail.setCreateTime(date);
        companyProfitDetail.setModifyTime(date);
        companyProfitDetail.setContent("订单" + order.getOrderNum() + "分成");
        companyProfitDetail.setDetail("+" + companyProfitBal);
        companyProfitDetail.setBal(platform.getCompanyProfitPool().toString());
        companyProfitDetail.setFromNum(order.getOrderNum());
        companyProfitDetail.setDescription("订单" + order.getOrderNum() + "交易商家让利分成");
        companyProfitDetail.setName(member.getName());
        companyProfitDetail.setPhone(member.getPhone());
        companyProfitDetailMapper.insertSelective(companyProfitDetail);

        //平台信息变更
        platformMapper.updateByPrimaryKeySelective(platform);


        //用户睿积分增加
        coreRecord = coreRecord.add(corePointsBal);
        up = up.add(corePointsBal);
        companyReport.setCoreBal("+" + corePointsBal);

        accountMapper.corePointsAdd(corePointsBal, account.getId());
        CoreDetail coreDetail = new CoreDetail();
        coreDetail.setModifyTime(date);
        coreDetail.setCreateTime(date);
        coreDetail.setContent("消费基数增加");
        coreDetail.setDetail("+" + corePointsBal);
        coreDetail.setaId(account.getId());
        coreDetail.setBal(accountMapper.selectByPrimaryKey(account.getId()).getCorePoints().toString());
        coreDetail.setName(member.getName());
        coreDetail.setPhone(member.getPhone());
        coreDetail.setFromNum(order.getOrderNum());
        coreDetailMapper.insertSelective(coreDetail);

        //商家货款增加(已删除该功能)


        //将用户的所有睿积分自动生成挂买单
        MskBuyOrder mskBuyOrder = new MskBuyOrder();
        mskBuyOrder.setCorePoints(account.getCorePoints().add(corePointsBal));
        mskBuyOrder.setCreateTime(date);
        mskBuyOrder.setmId(member.getId());
        mskBuyOrder.setModifyTime(date);
        mskBuyOrder.setName(member.getName());
        mskBuyOrder.setPhone(member.getPhone());
        mskBuyOrderMapper.insertSelective(mskBuyOrder);
        //用户睿积分挂单减少
        coreRecord = coreRecord.subtract(account.getCorePoints().add(corePointsBal));
        up = up.subtract(account.getCorePoints().add(corePointsBal));
        companyReport.setCoreBal(companyReport.getCoreBal() + "-" + account.getCorePoints().add(corePointsBal) + "\r\n=" + accountMapper.countCoreNum().add(coreRecord));

        accountMapper.corePointsSubtract(account.getCorePoints().add(corePointsBal), account.getId());
        CoreDetail coreDetail1 = new CoreDetail();
        coreDetail1.setModifyTime(date);
        coreDetail1.setCreateTime(date);
        coreDetail1.setContent("消费基数自动挂单");
        coreDetail1.setDetail("-" + account.getCorePoints().add(corePointsBal));
        coreDetail1.setaId(account.getId());
        coreDetail1.setBal(accountMapper.selectByPrimaryKey(account.getId()).getCorePoints().toString());
        coreDetail1.setName(member.getName());
        coreDetail1.setPhone(member.getPhone());
        coreDetail1.setFromNum("");
        coreDetailMapper.insertSelective(coreDetail1);


        if (memberUp != null) {
            //如果上级是原积分用户，且含有原积分
            if (memberUp.getMemberType().equals("original")) {
                Account accountUp = accountMapper.selectByMid(memberUp.getId());
                if (accountUp.getOriginalIntegral().compareTo(new BigDecimal("0")) == 1) {
                    if (accountUp.getOriginalIntegral().compareTo(corePointsBal.setScale(0, BigDecimal.ROUND_DOWN)) == 1) {
                        //有原积分，且原积分剩余大于要转换的个数
                        BigDecimal newNumber = corePointsBal.setScale(0, BigDecimal.ROUND_DOWN);
                        //原积分减少
                        accountMapper.originalSubtract(newNumber, accountUp.getId());
                        OriginalDetail originalDetail = new OriginalDetail();
                        originalDetail.setModifyTime(date);
                        originalDetail.setCreateTime(date);
                        originalDetail.setContent("扣除积分");
                        originalDetail.setDetail("-" + newNumber);
                        originalDetail.setaId(accountUp.getId());
                        originalDetail.setBal(accountMapper.selectByMid(memberUp.getId()).getOriginalIntegral().toString());
                        originalDetail.setName(memberUp.getName());
                        originalDetail.setPhone(memberUp.getPhone());
                        originalDetail.setFromNum(order.getOrderNum());
                        originalDetailMapper.insertSelective(originalDetail);

                        //公司msk账户增加对应数量msk
                        platformMapper.companyMskAdd(newNumber, 1L);
                        CompanyCompanyMsDetail companyCompanyMsDetail = new CompanyCompanyMsDetail();
                        companyCompanyMsDetail.setCreateTime(date);
                        companyCompanyMsDetail.setModifyTime(date);
                        companyCompanyMsDetail.setContent("订单" + order.getOrderNum() + "消费，原积分用户原积分转化成MS卖给公司,公司MS增加");
                        companyCompanyMsDetail.setDetail("+" + newNumber);
                        companyCompanyMsDetail.setBal(platformMapper.selectByPrimaryKey(1L).getCompanyMsk().toString());
                        companyCompanyMsDetail.setDescription("订单" + order.getOrderNum() + "消费，原积分用户原积分转化成MS卖给公司,公司MS增加");
                        companyCompanyMsDetail.setFromNum(order.getOrderNum());
                        companyCompanyMsDetail.setName(memberUp.getName());
                        companyCompanyMsDetail.setPhone(memberUp.getPhone());
                        companyCompanyMsDetailMapper.insertSelective(companyCompanyMsDetail);

                        //市场资金池扣除对应金额用于支付给原积分用户卖出的msk
                        marketFundRecord = marketFundRecord.add(new BigDecimal("-" + newNumber));
                        up = up.subtract(newNumber);
                        companyReport.setMarketFund(companyReport.getMarketFund() + "-" + newNumber);
                        platformMapper.marketFundPoolSubtract(newNumber, 1L);
                        CompanyMarketDetail companyMarketDetail1 = new CompanyMarketDetail();
                        companyMarketDetail1.setCreateTime(date);
                        companyMarketDetail1.setModifyTime(date);
                        companyMarketDetail1.setContent("订单" + order.getOrderNum() + "消费，原积分用户原积分转化成MS卖给公司,市场资金池支付给原积分用户");
                        companyMarketDetail1.setDetail("-" + newNumber);
                        companyMarketDetail1.setName(memberUp.getName());
                        companyMarketDetail1.setPhone(memberUp.getPhone());
                        companyMarketDetail1.setFromNum(order.getOrderNum());
                        companyMarketDetail1.setBal(platformMapper.selectByPrimaryKey(1L).getMarketFundPool().toString());
                        companyMarketDetail1.setDescription("订单" + order.getOrderNum() + "消费，原积分用户原积分转化成MS卖给公司,市场资金池支付给原积分用户");
                        companyMarketDetailMapper.insertSelective(companyMarketDetail1);

                        //卖出原积分手续费、分润账户得到的金额、消费账户得到的金额
                        BigDecimal mskPoundage = newNumber.multiply(poundageConfig.getMskSale()).divide(new BigDecimal("100"), 2, ROUND_HALF_DOWN);
                        BigDecimal mskP = newNumber.multiply(poundageConfig.getMskSaleP()).divide(new BigDecimal("100"), 2, ROUND_HALF_DOWN);
                        BigDecimal mskC = newNumber.subtract(mskPoundage).subtract(mskP);

                        //公司手续费池资金增加
                        withdrawPoundageRecord = mskPoundage;
                        up = up.add(mskPoundage);
                        companyReport.setWithdrawPoundage("+" + mskPoundage);
                        platformMapper.poundagePoolAdd(mskPoundage, 1L);
                        CompanyPoundageDetail companyPoundageDetail = new CompanyPoundageDetail();
                        companyPoundageDetail.setCreateTime(date);
                        companyPoundageDetail.setModifyTime(date);
                        companyPoundageDetail.setContent("订单" + order.getOrderNum() + "消费，原积分用户原积分转化成MS卖给公司,MS卖出获得手续费");
                        companyPoundageDetail.setDetail("+" + mskPoundage);
                        companyPoundageDetail.setBal(platformMapper.selectByPrimaryKey(1L).getPoundagePool().toString());
                        companyPoundageDetail.setFromNum(order.getOrderNum());
                        companyPoundageDetail.setDescription("订单" + order.getOrderNum() + "消费，原积分用户原积分转化成MS卖给公司,MS卖出获得手续费");
                        companyPoundageDetail.setName(memberUp.getName());
                        companyPoundageDetail.setPhone(memberUp.getPhone());
                        companyPoundageDetailMapper.insertSelective(companyPoundageDetail);

                        //原积分用户利润账户增加
                        profitRecord = profitRecord.add(mskP);
                        up = up.add(mskP);
                        companyReport.setProfitBal((companyReport.getProfitBal()!=null?companyReport.getProfitBal():"") + "+" + mskP);

                        accountMapper.profitAdd(mskP, accountUp.getId());
                        ProfitDetail profitDetailUp = new ProfitDetail();
                        profitDetailUp.setModifyTime(date);
                        profitDetailUp.setCreateTime(date);
                        profitDetailUp.setContent("卖出MS");
                        profitDetailUp.setDetail("+" + mskP);
                        profitDetailUp.setaId(accountUp.getId());
                        profitDetailUp.setBal(accountMapper.selectByPrimaryKey(accountUp.getId()).getProfit().toString());
                        profitDetailUp.setFromNum(order.getOrderNum());
                        profitDetailUp.setName(memberUp.getName());
                        profitDetailUp.setPhone(memberUp.getPhone());
                        profitDetailMapper.insertSelective(profitDetailUp);
                        //原积分用户消费账户增加
                        consumeRecord = consumeRecord.add(mskC);
                        up = up.add(mskC);
                        companyReport.setConsumeBal((companyReport.getConsumeBal()!=null?companyReport.getConsumeBal():"") + "+" + mskC);

                        accountMapper.consumptionAdd(mskC, accountUp.getId());
                        ConsumptionDetail consumptionDetail = new ConsumptionDetail();
                        consumptionDetail.setModifyTime(date);
                        consumptionDetail.setCreateTime(date);
                        consumptionDetail.setContent("卖出MS");
                        consumptionDetail.setDetail("+" + mskC);
                        consumptionDetail.setaId(accountUp.getId());
                        consumptionDetail.setBal(accountMapper.selectByMid(memberUp.getId()).getConsumption().toString());
                        consumptionDetail.setFromNum("");
                        consumptionDetail.setName(memberUp.getName());
                        consumptionDetail.setPhone(memberUp.getPhone());
                        consumptionDetailMapper.insertSelective(consumptionDetail);

                    } else {
                        //有原积分，且积分不足扣除，全部转换掉
                        BigDecimal newNumber = accountUp.getOriginalIntegral();
                        //原积分减少
                        accountMapper.originalSubtract(newNumber, accountUp.getId());
                        OriginalDetail originalDetail = new OriginalDetail();
                        originalDetail.setModifyTime(date);
                        originalDetail.setCreateTime(date);
                        originalDetail.setContent("扣除积分");
                        originalDetail.setDetail("-" + newNumber);
                        originalDetail.setaId(accountUp.getId());
                        originalDetail.setBal(accountMapper.selectByMid(memberUp.getId()).getOriginalIntegral().toString());
                        originalDetail.setName(memberUp.getName());
                        originalDetail.setPhone(memberUp.getPhone());
                        originalDetail.setFromNum(order.getOrderNum());
                        originalDetailMapper.insertSelective(originalDetail);

                        //公司msk账户增加对应数量msk
                        platformMapper.companyMskAdd(newNumber, 1L);
                        CompanyCompanyMsDetail companyCompanyMsDetail = new CompanyCompanyMsDetail();
                        companyCompanyMsDetail.setCreateTime(date);
                        companyCompanyMsDetail.setModifyTime(date);
                        companyCompanyMsDetail.setContent("订单" + order.getOrderNum() + "消费，原积分用户原积分转化成MS卖给公司,公司MS增加");
                        companyCompanyMsDetail.setDetail("+" + newNumber);
                        companyCompanyMsDetail.setBal(platformMapper.selectByPrimaryKey(1L).getCompanyMsk().toString());
                        companyCompanyMsDetail.setDescription("订单" + order.getOrderNum() + "消费，原积分用户原积分转化成MS卖给公司,公司MS增加");
                        companyCompanyMsDetail.setFromNum(order.getOrderNum());
                        companyCompanyMsDetail.setName(memberUp.getName());
                        companyCompanyMsDetail.setPhone(memberUp.getPhone());
                        companyCompanyMsDetailMapper.insertSelective(companyCompanyMsDetail);

                        //市场资金池扣除对应金额用于支付给原积分用户卖出的msk
                        marketFundRecord = marketFundRecord.add(new BigDecimal("-" + newNumber));
                        up = up.subtract(newNumber);
                        companyReport.setMarketFund(companyReport.getMarketFund() + "-" + newNumber);

                        platformMapper.marketFundPoolSubtract(newNumber, 1L);
                        CompanyMarketDetail companyMarketDetail1 = new CompanyMarketDetail();
                        companyMarketDetail1.setCreateTime(date);
                        companyMarketDetail1.setModifyTime(date);
                        companyMarketDetail1.setContent("订单" + order.getOrderNum() + "消费，原积分用户原积分转化成MS卖给公司,市场资金池支付给原积分用户");
                        companyMarketDetail1.setDetail("-" + newNumber);
                        companyMarketDetail1.setName(memberUp.getName());
                        companyMarketDetail1.setPhone(memberUp.getPhone());
                        companyMarketDetail1.setFromNum(order.getOrderNum());
                        companyMarketDetail1.setBal(platformMapper.selectByPrimaryKey(1L).getMarketFundPool().toString());
                        companyMarketDetail1.setDescription("订单" + order.getOrderNum() + "消费，原积分用户原积分转化成MS卖给公司,市场资金池支付给原积分用户");
                        companyMarketDetailMapper.insertSelective(companyMarketDetail1);

                        //卖出原积分手续费、分润账户得到的金额、消费账户得到的金额
                        BigDecimal mskPoundage = newNumber.multiply(poundageConfig.getMskSale()).divide(new BigDecimal("100"), 2, ROUND_HALF_DOWN);
                        BigDecimal mskP = newNumber.multiply(poundageConfig.getMskSaleP()).divide(new BigDecimal("100"), 2, ROUND_HALF_DOWN);
                        BigDecimal mskC = newNumber.subtract(mskPoundage).subtract(mskP);

                        //公司手续费池资金增加
                        withdrawPoundageRecord = mskPoundage;
                        up = up.add(mskPoundage);
                        companyReport.setWithdrawPoundage("+" + mskPoundage);

                        platformMapper.poundagePoolAdd(mskPoundage, 1L);
                        CompanyPoundageDetail companyPoundageDetail = new CompanyPoundageDetail();
                        companyPoundageDetail.setCreateTime(date);
                        companyPoundageDetail.setModifyTime(date);
                        companyPoundageDetail.setContent("订单" + order.getOrderNum() + "消费，原积分用户原积分转化成MS卖给公司,MS卖出获得手续费");
                        companyPoundageDetail.setDetail("+" + mskPoundage);
                        companyPoundageDetail.setBal(platformMapper.selectByPrimaryKey(1L).getPoundagePool().toString());
                        companyPoundageDetail.setFromNum(order.getOrderNum());
                        companyPoundageDetail.setDescription("订单" + order.getOrderNum() + "消费，原积分用户原积分转化成MS卖给公司,MS卖出获得手续费");
                        companyPoundageDetail.setName(memberUp.getName());
                        companyPoundageDetail.setPhone(memberUp.getPhone());
                        companyPoundageDetailMapper.insertSelective(companyPoundageDetail);

                        //原积分用户利润账户增加
                        profitRecord = profitRecord.add(mskP);
                        up = up.add(mskP);
                        companyReport.setProfitBal((companyReport.getProfitBal()!=null?companyReport.getProfitBal():"") + "+" + mskP);


                        accountMapper.profitAdd(mskP, accountUp.getId());
                        ProfitDetail profitDetailUp = new ProfitDetail();
                        profitDetailUp.setModifyTime(date);
                        profitDetailUp.setCreateTime(date);
                        profitDetailUp.setContent("卖出MS");
                        profitDetailUp.setDetail("+" + mskP);
                        profitDetailUp.setaId(accountUp.getId());
                        profitDetailUp.setBal(accountMapper.selectByPrimaryKey(accountUp.getId()).getProfit().toString());
                        profitDetailUp.setFromNum(order.getOrderNum());
                        profitDetailUp.setName(memberUp.getName());
                        profitDetailUp.setPhone(memberUp.getPhone());
                        profitDetailMapper.insertSelective(profitDetailUp);
                        //原积分用户消费账户增加
                        consumeRecord = consumeRecord.add(mskC);
                        up = up.add(mskC);
                        companyReport.setConsumeBal((companyReport.getConsumeBal()!=null?companyReport.getConsumeBal():"") + "+" + mskC);

                        accountMapper.consumptionAdd(mskC, accountUp.getId());
                        ConsumptionDetail consumptionDetail = new ConsumptionDetail();
                        consumptionDetail.setModifyTime(date);
                        consumptionDetail.setCreateTime(date);
                        consumptionDetail.setContent("卖出MS");
                        consumptionDetail.setDetail("+" + mskC);
                        consumptionDetail.setaId(accountUp.getId());
                        consumptionDetail.setBal(accountMapper.selectByMid(memberUp.getId()).getConsumption().toString());
                        consumptionDetail.setFromNum(order.getOrderNum());
                        consumptionDetail.setName(memberUp.getName());
                        consumptionDetail.setPhone(memberUp.getPhone());
                        consumptionDetailMapper.insertSelective(consumptionDetail);
                    }
                }

            }
        }
        //分润余额
        companyReport.setProfitBal((companyReport.getProfitBal()!=null?companyReport.getProfitBal():"") + "\r\n=" + accountMapper.countProfitNum().add(profitRecord));
        //消费余额
        if(companyReport.getConsumeBal()!=null){
            companyReport.setConsumeBal(companyReport.getConsumeBal() + "\r\n=" + consumeRecord.add(accountMapper.countConsumeNum()));
        }
       //市场资金池
        companyReport.setMarketFund(companyReport.getMarketFund() + "\r\n=" + platform.getMarketFundPool().add(marketFundRecord));
        //公司提现手续费资金池
        companyReport.setWithdrawPoundage(companyReport.getWithdrawPoundage()!=null?(companyReport.getWithdrawPoundage()+"\r\n=" + platform.getPoundagePool().add(withdrawPoundageRecord)):"");

        companyReport.setTotal(up.toString()+"\r\n="+countTotalVal(companyReport));

        companyReportMapper.insertSelective(companyReport);
        //更新订单支付状态
        Order update = new Order();
        update.setStatus(3);
        update.setId(order.getId());
        orderMapper.updateByPrimaryKeySelective(update);

    }

    public static BigDecimal countTotalVal(CompanyReport companyReport) {
        BigDecimal blow = new BigDecimal("0");

        if (companyReport.getMarketFund() != null && companyReport.getMarketFund().indexOf("=") != -1) {
            blow = blow.add(countTotal(companyReport.getMarketFund()));
        }
        if (companyReport.getCompanyFund() != null && companyReport.getCompanyFund().indexOf("=") != -1) {
            blow = blow.add(countTotal(companyReport.getCompanyFund()));
        }
        if (companyReport.getProfitBal()!=null && companyReport.getProfitBal().indexOf("=") != -1) {
            blow = blow.add(countTotal(companyReport.getProfitBal()));
        }
        if (companyReport.getCoreBal() != null && companyReport.getCoreBal().indexOf("=") != -1) {
            blow = blow.add(countTotal(companyReport.getCoreBal()));
        }
        if (companyReport.getUnWithdraw() != null && companyReport.getUnWithdraw().indexOf("=") != -1) {
            blow = blow.add(countTotal(companyReport.getUnWithdraw()));
        }
        if (companyReport.getPoundage() != null && companyReport.getPoundage().indexOf("=") != -1) {
            blow = blow.add(countTotal(companyReport.getPoundage()));
        }
        if (companyReport.getWithdrawPoundage() != null && companyReport.getWithdrawPoundage().indexOf("=") != -1) {
            blow = blow.add(countTotal(companyReport.getWithdrawPoundage()));
        }
        if (companyReport.getCompanyProfit() != null && companyReport.getCompanyProfit().indexOf("=") != -1) {
            blow = blow.add(countTotal(companyReport.getCompanyProfit()));
        }
        if (companyReport.getConsumeBal() != null && companyReport.getConsumeBal().indexOf("=") != -1) {
            blow = blow.add(countTotal(companyReport.getConsumeBal()));
        }
        return blow;
    }

    public static BigDecimal countTotal(String val) {
        if (val != null && val.indexOf("=") != -1) {
            return new BigDecimal(val.split("=")[val.split("=").length - 1]);
        } else {
            return new BigDecimal("0");
        }
    }

}
